package com.qf.fmall2202.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.fmall2202.user.entity.Users;
import com.qf.fmall2202.user.mapper.UsersMapper;
import com.qf.fmall2202.user.service.IUsersService;
import com.qf.fmall2202.user.shiro.ShiroConstants;
import com.qf.fmall2202.utils.R;
import com.qf.fmall2202.utils.SaltUtils;
import com.qf.fmall2202.utils.TokenUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 用户  服务实现类
 * </p>
 *
 * @author author
 * @since 2022-11-03
 */
@Service
public class UsersServiceImpl extends ServiceImpl< UsersMapper, Users > implements IUsersService {

	@Override
	public R goRegist( Users users ) {

		R r=new R( );


		if(users.getPassword().equals( users.getRepassword() )) {
			String salts=SaltUtils.getSalts( );
			users.setSalt( salts );

			//加密密码
			String s=new SimpleHash( ShiroConstants.hashAlgorithmName,users.getPassword( ),salts,ShiroConstants.hashIterations ).toString( );

			users.setPassword( s );

			users.setUserRegtime( new Date(  ) );

			users.setUserModtime( new Date(  ) );

			boolean save=this.save( users );


			if(save){
				r.setCode( 10000 );
			}else {
				r.setCode( 10001 );
			}
		}else {
			r.setCode( 10001 );
		}


		return r;
	}

	@Override
	public R goLogin( Users users ) {
		R r=new R( );
		//生成token
		String token=TokenUtils.getToken( users );

		Subject subject=SecurityUtils.getSubject( );
		UsernamePasswordToken token1=new UsernamePasswordToken( users.getUsername( ),users.getPassword( ) );


		try {
			subject.login(token1);
		} catch(Exception e) {
			r.setCode( 10001 );
		}

		r.setCode( 10000 );
		r.setMsg( token );

		Users user=(Users) SecurityUtils.getSubject( ).getPrincipal( );

		r.setData( user );

		return r ;
	}


}
